const categoryModel = require('../models/categoryModel');
const { sendSuccess, sendError } = require('../utils/response');

module.exports = {
  // 获取所有分类
  async getAllCategories(req, res) {
    try {
      const categories = await categoryModel.getAllCategories();
      sendSuccess(res, categories);
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 获取分类详情
  async getCategory(req, res) {
    try {
      const { id } = req.params;
      const category = await categoryModel.getCategoryById(id);
      sendSuccess(res, category);
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 创建分类
  async createCategory(req, res) {
    try {
      const { name_en, name_cn, icon_class } = req.body;
      
      if (!name_en || !name_cn || !icon_class) {
        return sendError(res, '请填写完整分类信息', 400);
      }
      
      const categoryId = await categoryModel.createCategory(name_en, name_cn, icon_class);
      const category = await categoryModel.getCategoryById(categoryId);
      sendSuccess(res, category, '分类创建成功', 201);
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 更新分类
  async updateCategory(req, res) {
    try {
      const { id } = req.params;
      const { name_en, name_cn, icon_class } = req.body;
      
      await categoryModel.updateCategory(id, name_en, name_cn, icon_class);
      const category = await categoryModel.getCategoryById(id);
      sendSuccess(res, category, '分类更新成功');
    } catch (err) {
      sendError(res, err.message);
    }
  },

  // 删除分类
  async deleteCategory(req, res) {
    try {
      const { id } = req.params;
      
      await categoryModel.deleteCategory(id);
      sendSuccess(res, null, '分类删除成功');
    } catch (err) {
      sendError(res, err.message);
    }
  }
};